/**
 * Copyright (c) 2010-2011 by Kevin Bierhoff.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *    1. Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *    3. Neither the names of the authors nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.googlecode.syper.vstte12.problem1;

import com.googlecode.syper.anno.BoundsChecks;
import com.googlecode.syper.anno.Excl;
import com.googlecode.syper.anno.NullChecks;

import edu.cmu.cs.crystal.annotations.PassingTest;
import edu.cmu.cs.crystal.annotations.UseAnalyses;

/**
 * <b><a href="https://sites.google.com/site/vstte2012/compet">VSTTE 2012 
 * Verification Challenge</a> Problem 1: Two-Way Sort</b>.
 * <p>
 * We want to sort an array of Boolean values (assuming false < true) using only swaps.
 * Verification tasks:
 * <ol>
 * <li><i>Safety:</i> Verify that every array access is made within bounds. 
 * Verified with {@link BoundsChecks} annotation throughout this class.
 * <li><i>Termination:</i> Prove that {@link #twoWaySort(boolean[])} always terminates.
 * Verified with assertions of descending measuring function.
 * <li><i>Behavior:</i> Verify that after the execution of {@link #twoWaySort(boolean[])},
 * the given array is (a) sorted in increasing order and is (b) a permutation of 
 * its initial contents.  Verified with appropriate post-conditions.
 * </ol>
 * @author kevin
 * @since Nov 8, 2011
 */
@BoundsChecks // 1. checks that array accesses in bounds
@NullChecks   // checks absence of NPEs
@PassingTest
@UseAnalyses("SymbolicChecker")
public final class BinarySort {

	/**
	 * sorts a {@code boolean} array in ascending order ({@code false} before 
	 * {@code true}) using only {@link #swap(boolean[], int, int)} operations.
	 * Termination is proved with simple {@code assert} statements to compensate
	 * for the absence of support for {@code decreasing} JML specs in JavaSyp.
	 * @param a
	 */
	//@ requires a != null;
	// 3(a) array a is sorted in increasing order:
	//@ ensures (\forall int l; 0 <= l & l < a.length;
	//@  	(\forall int k; 0 <= k & k <= l; a[k] == false | a[k] == a[l]) & 
	//@  	(\forall int k; l <= k & k < a.length; a[k] == true | a[k] == a[l]));
	// 3(b) array a is a permutation of the initial contents:
	//@ ensures (\forall int k; 0 <= k & k < a.length; (\exists int l; 0 <= l & l < a.length; a[k] == \old(a[l])));
	public static void twoWaySort(@Excl final boolean[] a) {
		int i = 0;
		int j = a.length - 1;
		assert -1 <= (j - i);
		//@ maintaining 0 <= i & i <= a.length;
		//@ maintaining -1 <= j & j < a.length;
		//@ maintaining (\forall int k; 0 <= k & k < i; a[k] == false);
		//@ maintaining (\forall int k; j < k & k < a.length; a[k] == true);
		//@ decreasing j - i + 1; // not verified: "decreasing" clauses not supported
		while (i <= j) {
			int oldI = i; int oldJ = j;
			if (!a[i]) {
				++i;
			} else if (a[j]) {
				--j;
			} else {
				swap(a, i, j);
				++i;
				--j;
			}
			// 2. proves termination... (together with the other 2 assert stmts in the method)
			assert (j - i) < (oldJ - oldI);
		}
		assert (j - i) <= -1;
	}
	
	//@ requires a != null;
	//@ requires 0 <= i & i < a.length;
	//@ requires 0 <= j & j < a.length;
	//@ ensures a[i] == \old(a[j]);
	//@ ensures a[j] == \old(a[i]);
	//@ ensures (\forall int k; 0 <= k & k < a.length & k != i & k != j; a[k] == \old(a[k]));
	private static void swap(@Excl final boolean[] a, final int i, final int j) {
		boolean t = a[i];
		a[i] = a[j];
		a[j] = t;
	}
}
